package com.bigdatan.b2c.service.impl;

import com.bigdatan.b2c.controller.glass.vo.CategoryVO;
import com.bigdatan.b2c.entity.ProductCategory;
import com.bigdatan.b2c.service.IProductCategoryService;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by shangdong on 17/6/25.
 */
@Component
public class GlassCategoryServiceImpl {

    @Resource
    private IProductCategoryService productCategoryService;

    public static final Function<ProductCategory, CategoryVO> productCategoryCategoryVOFunction = productCategory -> {
        CategoryVO categoryVO = new CategoryVO();
        BeanUtils.copyProperties(productCategory, categoryVO);
        return categoryVO;
    };


    public List<CategoryVO> getAllCategory(){
        List<CategoryVO> res = Lists.newArrayList();
        List<ProductCategory> productCategoryList = productCategoryService
                .getAllNormalFirstLevelCategory();
        List<CategoryVO> categoryVOs;
        categoryVOs = Lists.transform(productCategoryList, productCategoryCategoryVOFunction);
        categoryVOs = Lists.newArrayList(categoryVOs);
        Comparator<CategoryVO> categoryVOComparator = (o1, o2) -> new Integer(o1.getCategoryId()).compareTo(new Integer(o2.getCategoryId()));
        for (CategoryVO categoryVO : categoryVOs) {
            List<ProductCategory> childs = productCategoryService.getAllNormalChildCategoryByCategoryId(categoryVO.getCategoryId());
            List<CategoryVO> childsVO = Lists.transform(childs, productCategoryCategoryVOFunction);
            List<CategoryVO> childsVOList = Lists.newArrayList(childsVO);
            Collections.sort(childsVOList, categoryVOComparator);
            categoryVO.setChilds(childsVOList);
        }
        return categoryVOs;
    }


    public List<String> getCategoryName(List<CategoryVO> categoryVOs,Integer categoryID){
        List<String> res = new ArrayList<>();
        for (CategoryVO categoryVO : categoryVOs) {
            if (categoryVO.getCategoryId() == categoryID){
                res.add(categoryVO.getCategoryName());
                break;
            }
            for (CategoryVO vo : categoryVO.getChilds()) {
               if (vo.getCategoryId() == categoryID){
                   res.add(categoryVO.getCategoryName());
                   res.add(vo.getCategoryName());
                   break;
               }
            }
        }
        return res;
    }
}
